<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>10.8. Zend_Db_Table Relationships</title>
<link rel="stylesheet" href="dbstyle.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.72.0">
<link rel="start" href="index.html" title="Programmer's Reference Guide">
<link rel="up" href="zend.db.html" title="Chapter 10. Zend_Db">
<link rel="prev" href="zend.db.table.rowset.html" title="10.7. Zend_Db_Table_Rowset">
<link rel="next" href="zend.debug.html" title="Chapter 11. Zend_Debug">
<link rel="chapter" href="introduction.html" title="Chapter 1. Introduction to Zend Framework">
<link rel="chapter" href="zend.acl.html" title="Chapter 2. Zend_Acl">
<link rel="chapter" href="zend.auth.html" title="Chapter 3. Zend_Auth">
<link rel="chapter" href="zend.cache.html" title="Chapter 4. Zend_Cache">
<link rel="chapter" href="zend.config.html" title="Chapter 5. Zend_Config">
<link rel="chapter" href="zend.console.getopt.html" title="Chapter 6. Zend_Console_Getopt">
<link rel="chapter" href="zend.controller.html" title="Chapter 7. Zend_Controller">
<link rel="chapter" href="zend.currency.html" title="Chapter 8. Zend_Currency">
<link rel="chapter" href="zend.date.html" title="Chapter 9. Zend_Date">
<link rel="chapter" href="zend.db.html" title="Chapter 10. Zend_Db">
<link rel="chapter" href="zend.debug.html" title="Chapter 11. Zend_Debug">
<link rel="chapter" href="zend.dojo.html" title="Chapter 12. Zend_Dojo">
<link rel="chapter" href="zend.dom.html" title="Chapter 13. Zend_Dom">
<link rel="chapter" href="zend.exception.html" title="Chapter 14. Zend_Exception">
<link rel="chapter" href="zend.feed.html" title="Chapter 15. Zend_Feed">
<link rel="chapter" href="zend.filter.html" title="Chapter 16. Zend_Filter">
<link rel="chapter" href="zend.form.html" title="Chapter 17. Zend_Form">
<link rel="chapter" href="zend.gdata.html" title="Chapter 18. Zend_Gdata">
<link rel="chapter" href="zend.http.html" title="Chapter 19. Zend_Http">
<link rel="chapter" href="zend.infocard.html" title="Chapter 20. Zend_InfoCard">
<link rel="chapter" href="zend.json.html" title="Chapter 21. Zend_Json">
<link rel="chapter" href="zend.layout.html" title="Chapter 22. Zend_Layout">
<link rel="chapter" href="zend.ldap.html" title="Chapter 23. Zend_Ldap">
<link rel="chapter" href="zend.loader.html" title="Chapter 24. Zend_Loader">
<link rel="chapter" href="zend.locale.html" title="Chapter 25. Zend_Locale">
<link rel="chapter" href="zend.log.html" title="Chapter 26. Zend_Log">
<link rel="chapter" href="zend.mail.html" title="Chapter 27. Zend_Mail">
<link rel="chapter" href="zend.measure.html" title="Chapter 28. Zend_Measure">
<link rel="chapter" href="zend.memory.html" title="Chapter 29. Zend_Memory">
<link rel="chapter" href="zend.mime.html" title="Chapter 30. Zend_Mime">
<link rel="chapter" href="zend.openid.html" title="Chapter 31. Zend_OpenId">
<link rel="chapter" href="zend.paginator.html" title="Chapter 32. Zend_Paginator">
<link rel="chapter" href="zend.pdf.html" title="Chapter 33. Zend_Pdf">
<link rel="chapter" href="zend.registry.html" title="Chapter 34. Zend_Registry">
<link rel="chapter" href="zend.rest.html" title="Chapter 35. Zend_Rest">
<link rel="chapter" href="zend.search.lucene.html" title="Chapter 36. Zend_Search_Lucene">
<link rel="chapter" href="zend.server.html" title="Chapter 37. Zend_Server">
<link rel="chapter" href="zend.service.html" title="Chapter 38. Zend_Service">
<link rel="chapter" href="zend.session.html" title="Chapter 39. Zend_Session">
<link rel="chapter" href="zend.soap.html" title="Chapter 40. Zend_Soap">
<link rel="chapter" href="zend.test.html" title="Chapter 41. Zend_Test">
<link rel="chapter" href="zend.text.html" title="Chapter 42. Zend_Text">
<link rel="chapter" href="zend.timesync.html" title="Chapter 43. Zend_TimeSync">
<link rel="chapter" href="zend.translate.html" title="Chapter 44. Zend_Translate">
<link rel="chapter" href="zend.uri.html" title="Chapter 45. Zend_Uri">
<link rel="chapter" href="zend.validate.html" title="Chapter 46. Zend_Validate">
<link rel="chapter" href="zend.version.html" title="Chapter 47. Zend_Version">
<link rel="chapter" href="zend.view.html" title="Chapter 48. Zend_View">
<link rel="chapter" href="zend.xmlrpc.html" title="Chapter 49. Zend_XmlRpc">
<link rel="appendix" href="requirements.html" title="Appendix A. Zend Framework Requirements">
<link rel="appendix" href="coding-standard.html" title="Appendix B. Zend Framework Coding Standard for PHP">
<link rel="appendix" href="copyrights.html" title="Appendix C. Copyright Information">
<link rel="index" href="the.index.html" title="Index">
<link rel="subsection" href="zend.db.table.relationships.html#zend.db.table.relationships.introduction" title="10.8.1. Introduction">
<link rel="subsection" href="zend.db.table.relationships.html#zend.db.table.relationships.defining" title="10.8.2. Defining Relationships">
<link rel="subsection" href="zend.db.table.relationships.html#zend.db.table.relationships.fetching.dependent" title="10.8.3. Fetching a Dependent Rowset">
<link rel="subsection" href="zend.db.table.relationships.html#zend.db.table.relationships.fetching.parent" title="10.8.4. Fetching a Parent Row">
<link rel="subsection" href="zend.db.table.relationships.html#zend.db.table.relationships.fetching.many-to-many" title="10.8.5. Fetching a Rowset via a Many-to-many Relationship">
<link rel="subsection" href="zend.db.table.relationships.html#zend.db.table.relationships.cascading" title="10.8.6. Cascading Write Operations">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader"><table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">10.8. Zend_Db_Table Relationships</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="zend.db.table.rowset.html">Prev</a> </td>
<th width="60%" align="center">Chapter 10. Zend_Db</th>
<td width="20%" align="right"> <a accesskey="n" href="zend.debug.html">Next</a>
</td>
</tr>
</table></div>
<div class="sect1" lang="en">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="zend.db.table.relationships"></a>10.8. Zend_Db_Table Relationships</h2></div></div></div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.db.table.relationships.introduction"></a>10.8.1. Introduction</h3></div></div></div>
<p>
            Tables have relationships to each other in a relational database. An entity in one
            table can be linked to one or more entities in another table by using referential
            integrity constraints defined in the database schema.
        </p>
<p>
            The Zend_Db_Table_Row class has methods for querying related rows in other tables.
        </p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.db.table.relationships.defining"></a>10.8.2. Defining Relationships</h3></div></div></div>
<p>
            Define classes for each of your tables, extending the abstract class
            Zend_Db_Table_Abstract, as described in <a href="zend.db.table.html#zend.db.table.defining" title="10.5.2. Defining a Table Class">Section 10.5.2, “Defining a Table Class”</a>. Also
            see <a href="zend.db.html#zend.db.adapter.example-database" title="10.1.2. The example database">Section 10.1.2, “The example database”</a> for a description of the
            example database for which the following example code is designed.
        </p>
<p>
            Below are the PHP class definitions for these tables:
        </p>
<pre class="programlisting">&lt;?php
class Accounts extends Zend_Db_Table_Abstract
{
    protected $_name            = 'accounts';
    protected $_dependentTables = array('Bugs');
}

class Products extends Zend_Db_Table_Abstract
{
    protected $_name            = 'products';
    protected $_dependentTables = array('BugsProducts');
}

class Bugs extends Zend_Db_Table_Abstract
{
    protected $_name            = 'bugs';

    protected $_dependentTables = array('BugsProducts');

    protected $_referenceMap    = array(
        'Reporter' =&gt; array(
            'columns'           =&gt; 'reported_by',
            'refTableClass'     =&gt; 'Accounts',
            'refColumns'        =&gt; 'account_name'
        ),
        'Engineer' =&gt; array(
            'columns'           =&gt; 'assigned_to',
            'refTableClass'     =&gt; 'Accounts',
            'refColumns'        =&gt; 'account_name'
        ),
        'Verifier' =&gt; array(
            'columns'           =&gt; array('verified_by'),
            'refTableClass'     =&gt; 'Accounts',
            'refColumns'        =&gt; array('account_name')
        )
    );
}

class BugsProducts extends Zend_Db_Table_Abstract
{
    protected $_name = 'bugs_products';

    protected $_referenceMap    = array(
        'Bug' =&gt; array(
            'columns'           =&gt; array('bug_id'),
            'refTableClass'     =&gt; 'Bugs',
            'refColumns'        =&gt; array('bug_id')
        ),
        'Product' =&gt; array(
            'columns'           =&gt; array('product_id'),
            'refTableClass'     =&gt; 'Products',
            'refColumns'        =&gt; array('product_id')
        )
    );

}
        </pre>
<p>
            If you use Zend_Db_Table to emulate cascading UPDATE and DELETE operations, declare the
            <code class="code">$_dependentTables</code> array in the class for the parent table. List the class
            name for each dependent table. Use the class name, not the physical name of the SQL
            table.
        </p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
                Skip declaration of <code class="code">$_dependentTables</code> if you use referential integrity
                constraints in the RDBMS server to implement cascading operations. See
                <a href="zend.db.table.relationships.html#zend.db.table.relationships.cascading" title="10.8.6. Cascading Write Operations">Section 10.8.6, “Cascading Write Operations”</a> for more information.
            </p></td></tr>
</table></div>
<p>
            Declare the <code class="code">$_referenceMap</code> array in the class for each dependent table.
            This is an associative array of reference "rules". A reference rule identifies which
            table is the parent table in the relationship, and also lists which columns in the
            dependent table reference which columns in the parent table.
        </p>
<p>
            The rule key is a string used as an index to the <code class="code">$_referenceMap</code> array.
            This rule key is used to identify each reference relationship. Choose a descriptive
            name for this rule key. It's best to use a string that can be part of a PHP method
            name, as you will see later.
        </p>
<p>
            In the example PHP code above, the rule keys in the Bugs table class are:
            <code class="code">'Reporter'</code>, <code class="code">'Engineer'</code>, <code class="code">'Verifier'</code>, and
            <code class="code">'Product'</code>.
        </p>
<p>
            The value of each rule entry in the <code class="code">$_referenceMap</code> array is also an
            associative array. The elements of this rule entry are described below:
        </p>
<div class="itemizedlist"><ul type="disc">
<li>
<p>
                    <span class="strong"><strong>columns</strong></span> =&gt; A string or an array of strings
                    naming the foreign key column name(s) in the dependent table.
                </p>
<p>
                    It's common for this to be a single column, but some tables have multi-column
                    keys.
                </p>
</li>
<li>
<p>
                    <span class="strong"><strong>refTableClass</strong></span> =&gt; The class name of the
                    parent table. Use the class name, not the physical name of the SQL table.
                </p>
<p>
                    It's common for a dependent table to have only one reference to its parent
                    table, but some tables have multiple references to the same parent table. In
                    the example database, there is one reference from the <code class="code">bugs</code> table
                    to the <code class="code">products</code> table, but three references from the
                    <code class="code">bugs</code> table to the <code class="code">accounts</code> table. Put each reference
                    in a separate entry in the <code class="code">$_referenceMap</code> array.
                </p>
</li>
<li>
<p>
                    <span class="strong"><strong>refColumns</strong></span> =&gt; A string or an array of
                    strings naming the primary key column name(s) in the parent table.
                </p>
<p>
                    It's common for this to be a single column, but some tables have multi-column
                    keys. If the reference uses a multi-column key, the order of columns in the
                    <code class="code">'columns'</code> entry must match the order of columns in the
                    <code class="code">'refColumns'</code> entry.
                </p>
<p>
                    It is optional to specify this element. If you don't specify the
                    <code class="code">refColumns</code>, the column(s) reported as the primary key columns of
                    the parent table are used by default.
                </p>
</li>
<li><p>
                    <span class="strong"><strong>onDelete</strong></span> =&gt; The rule for an action to
                    execute if a row is deleted in the parent table. See
                    <a href="zend.db.table.relationships.html#zend.db.table.relationships.cascading" title="10.8.6. Cascading Write Operations">Section 10.8.6, “Cascading Write Operations”</a> for more information.
                </p></li>
<li><p>
                    <span class="strong"><strong>onUpdate</strong></span> =&gt; The rule for an action to
                    execute if values in primary key columns are updated in the parent table. See
                    <a href="zend.db.table.relationships.html#zend.db.table.relationships.cascading" title="10.8.6. Cascading Write Operations">Section 10.8.6, “Cascading Write Operations”</a> for more information.
                </p></li>
</ul></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.db.table.relationships.fetching.dependent"></a>10.8.3. Fetching a Dependent Rowset</h3></div></div></div>
<p>
            If you have a Row object as the result of a query on a parent table, you can fetch rows
            from dependent tables that reference the current row. Use the method:
        </p>
<pre class="programlisting">
$row-&gt;findDependentRowset($table, [$rule]);
        </pre>
<p>
            This method returns a Zend_Db_Table_Rowset_Abstract object, containing a set of rows
            from the dependent table <code class="code">$table</code> that refer to the row identified by the
            <code class="code">$row</code> object.
        </p>
<p>
            The first argument <code class="code">$table</code> can be a string that specifies the dependent
            table by its class name. You can also specify the dependent table by using an object of
            that table class.
        </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.dependent.example"></a><p class="title"><b>Example 10.136. Fetching a Dependent Rowset</b></p>
<div class="example-contents">
<p>
                This example shows getting a Row object from the table <code class="code">Accounts</code>, and
                finding the <code class="code">Bugs</code> reported by that account.
            </p>
<pre class="programlisting">&lt;?php
$accountsTable      = new Accounts();
$accountsRowset     = $accountsTable-&gt;find(1234);
$user1234           = $accountsRowset-&gt;current();

$bugsReportedByUser = $user1234-&gt;findDependentRowset('Bugs');
            </pre>
</div>
</div>
<br class="example-break"><p>
            The second argument <code class="code">$rule</code> is optional. It is a string that names the rule
            key in the <code class="code">$_referenceMap</code> array of the dependent table class. If you don't
            specify a rule, the first rule in the array that references the parent table is used.
            If you need to use a rule other than the first, you need to specify the key.
        </p>
<p>
            In the example code above, the rule key is not specified, so the rule used by default
            is the first one that matches the parent table. This is the rule
            <code class="code">'Reporter'</code>.
        </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.dependent.example-by"></a><p class="title"><b>Example 10.137. Fetching a Dependent Rowset By a Specific Rule</b></p>
<div class="example-contents">
<p>
                This example shows getting a Row object from the table <code class="code">Accounts</code>, and
                finding the <code class="code">Bugs</code> assigned to be fixed by the user of that account. The
                rule key string that corresponds to this reference relationship in this example is
                <code class="code">'Engineer'</code>.
            </p>
<pre class="programlisting">&lt;?php
$accountsTable      = new Accounts();
$accountsRowset     = $accountsTable-&gt;find(1234);
$user1234           = $accountsRowset-&gt;current();

$bugsAssignedToUser = $user1234-&gt;findDependentRowset('Bugs', 'Engineer');
            </pre>
</div>
</div>
<br class="example-break"><p>
            You can also add criteria, ordering and limits to your relationships using the parent
            row's select object.
        </p>
<p>

            </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.dependent.example-by-select"></a><p class="title"><b>Example 10.138. Fetching a Dependent Rowset using a Zend_Db_Table_Select</b></p>
<div class="example-contents">
<p>
                    This example shows getting a Row object from the table <code class="code">Accounts</code>,
                    and finding the <code class="code">Bugs</code> assigned to be fixed by the user of that
                    account, limited only to 3 rows and ordered by name.
                </p>
<pre class="programlisting">&lt;?php
$accountsTable      = new Accounts();
$accountsRowset     = $accountsTable-&gt;find(1234);
$user1234           = $accountsRowset-&gt;current();
$select             = $accountsTable-&gt;select()-&gt;order('name ASC')
                                              -&gt;limit(3);

$bugsAssignedToUser = $user1234-&gt;findDependentRowset('Bugs', 'Engineer', $select);
                </pre>
</div>
</div>
<p><br class="example-break">

            Alternatively, you can query rows from a dependent table using a special mechanism
            called a "magic method". Zend_Db_Table_Row_Abstract invokes the method:
            <code class="code">findDependentRowset('&lt;TableClass&gt;', '&lt;Rule&gt;')</code> if you invoke a method on
            the Row object matching either of the following patterns:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                    <code class="code">$row-&gt;find&lt;TableClass&gt;()</code>
                </p></li>
<li><p>
                    <code class="code">$row-&gt;find&lt;TableClass&gt;By&lt;Rule&gt;()</code>
                </p></li>
</ul></div>
<p>
            In the patterns above, <code class="code">&lt;TableClass&gt;</code> and <code class="code">&lt;Rule&gt;</code> are strings
            that correspond to the class name of the dependent table, and the dependent table's
            rule key that references the parent table.
        </p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
                Some application frameworks, such as Ruby on Rails, use a mechanism called
                "inflection" to allow the spelling of identifiers to change depending on usage. For
                simplicity, Zend_Db_Table_Row does not provide any inflection mechanism. The table
                identity and the rule key named in the method call must match the spelling of the
                class and rule key exactly.
            </p></td></tr>
</table></div>
<div class="example">
<a name="zend.db.table.relationships.fetching.dependent.example-magic"></a><p class="title"><b>Example 10.139. Fetching Dependent Rowsets using the Magic Method</b></p>
<div class="example-contents">
<p>
                This example shows finding dependent Rowsets equivalent to those in the previous
                examples. In this case, the application uses the magic method invocation instead of
                specifying the table and rule as strings.
            </p>
<pre class="programlisting">&lt;?php
$accountsTable    = new Accounts();
$accountsRowset   = $accountsTable-&gt;find(1234);
$user1234         = $accountsRowset-&gt;current();

// Use the default reference rule
$bugsReportedBy   = $user1234-&gt;findBugs();

// Specify the reference rule
$bugsAssignedTo   = $user1234-&gt;findBugsByEngineer();
            </pre>
</div>
</div>
<br class="example-break">
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.db.table.relationships.fetching.parent"></a>10.8.4. Fetching a Parent Row</h3></div></div></div>
<p>
            If you have a Row object as the result of a query on a dependent table, you can fetch
            the row in the parent to which the dependent row refers. Use the method:
        </p>
<pre class="programlisting">
$row-&gt;findParentRow($table, [$rule]);
        </pre>
<p>
            There always should be exactly one row in the parent table referenced by a dependent
            row, therefore this method returns a Row object, not a Rowset object.
        </p>
<p>
            The first argument <code class="code">$table</code> can be a string that specifies the parent table
            by its class name. You can also specify the parent table by using an object of that
            table class.
        </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.parent.example"></a><p class="title"><b>Example 10.140. Fetching the Parent Row</b></p>
<div class="example-contents">
<p>
                This example shows getting a Row object from the table <code class="code">Bugs</code> (for
                example one of those bugs with status 'NEW'), and finding the row in the
                <code class="code">Accounts</code> table for the user who reported the bug.
            </p>
<pre class="programlisting">&lt;?php
$bugsTable         = new Bugs();
$bugsRowset        = $bugsTable-&gt;fetchAll(array('bug_status = ?' =&gt; 'NEW'));
$bug1              = $bugsRowset-&gt;current();

$reporter          = $bug1-&gt;findParentRow('Accounts');
            </pre>
</div>
</div>
<br class="example-break"><p>
            The second argument <code class="code">$rule</code> is optional. It is a string that names the rule
            key in the <code class="code">$_referenceMap</code> array of the dependent table class. If you don't
            specify a rule, the first rule in the array that references the parent table is used.
            If you need to use a rule other than the first, you need to specify the key.
        </p>
<p>
            In the example above, the rule key is not specified, so the rule used by default is the
            first one that matches the parent table. This is the rule <code class="code">'Reporter'</code>.
        </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.parent.example-by"></a><p class="title"><b>Example 10.141. Fetching a Parent Row By a Specific Rule</b></p>
<div class="example-contents">
<p>
                This example shows getting a Row object from the table <code class="code">Bugs</code>, and
                finding the account for the engineer assigned to fix that bug. The rule key string
                that corresponds to this reference relationship in this example is
                <code class="code">'Engineer'</code>.
            </p>
<pre class="programlisting">&lt;?php
$bugsTable         = new Bugs();
$bugsRowset        = $bugsTable-&gt;fetchAll(array('bug_status = ?', 'NEW'));
$bug1              = $bugsRowset-&gt;current();

$engineer          = $bug1-&gt;findParentRow('Accounts', 'Engineer');
            </pre>
</div>
</div>
<br class="example-break"><p>
            Alternatively, you can query rows from a parent table using a "magic method".
            Zend_Db_Table_Row_Abstract invokes the method:
            <code class="code">findParentRow('&lt;TableClass&gt;', '&lt;Rule&gt;')</code> if you invoke a method
            on the Row object matching either of the following patterns:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                    <code class="code">$row-&gt;findParent&lt;TableClass&gt;([Zend_Db_Table_Select $select])</code>
                </p></li>
<li><p>
                    <code class="code">$row-&gt;findParent&lt;TableClass&gt;By&lt;Rule&gt;([Zend_Db_Table_Select
                    $select])</code>
                </p></li>
</ul></div>
<p>
            In the patterns above, <code class="code">&lt;TableClass&gt;</code> and <code class="code">&lt;Rule&gt;</code>
            are strings that correspond to the class name of the parent table, and the dependent
            table's rule key that references the parent table.
        </p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
                The table identity and the rule key named in the method call must match the
                spelling of the class and rule key exactly.
            </p></td></tr>
</table></div>
<div class="example">
<a name="zend.db.table.relationships.fetching.parent.example-magic"></a><p class="title"><b>Example 10.142. Fetching the Parent Row using the Magic Method</b></p>
<div class="example-contents">
<p>
                This example shows finding parent Rows equivalent to those in the previous
                examples. In this case, the application uses the magic method invocation instead of
                specifying the table and rule as strings.
            </p>
<pre class="programlisting">&lt;?php
$bugsTable         = new Bugs();
$bugsRowset        = $bugsTable-&gt;fetchAll(array('bug_status = ?', 'NEW'));
$bug1              = $bugsRowset-&gt;current();

// Use the default reference rule
$reporter          = $bug1-&gt;findParentAccounts();

// Specify the reference rule
$engineer          = $bug1-&gt;findParentAccountsByEngineer();
            </pre>
</div>
</div>
<br class="example-break">
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.db.table.relationships.fetching.many-to-many"></a>10.8.5. Fetching a Rowset via a Many-to-many Relationship</h3></div></div></div>
<p>
            If you have a Row object as the result of a query on one table in a many-to-many
            relationship (for purposes of the example, call this the "origin" table), you can
            fetch corresponding rows in the other table (call this the "destination" table) via an
            intersection table. Use the method:
        </p>
<pre class="programlisting">
$row-&gt;findManyToManyRowset($table, $intersectionTable, [$rule1, [$rule2, [Zend_Db_Table_Select $select]]]);
        </pre>
<p>
            This method returns a Zend_Db_Table_Rowset_Abstract containing rows from the table
            <code class="code">$table</code>, satisfying the many-to-many relationship. The current Row object
            <code class="code">$row</code> from the origin table is used to find rows in the intersection table,
            and that is joined to the destination table.
        </p>
<p>
            The first argument <code class="code">$table</code> can be a string that specifies the destination
            table in the many-to-many relationship by its class name. You can also specify the
            destination table by using an object of that table class.
        </p>
<p>
            The second argument <code class="code">$intersectionTable</code> can be a string that specifies the
            intersection table between the two tables in the the many-to-many relationship by its
            class name. You can also specify the intersection table by using an object of that
            table class.
        </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.many-to-many.example"></a><p class="title"><b>Example 10.143. Fetching a Rowset with the Many-to-many Method</b></p>
<div class="example-contents">
<p>
                This example shows getting a Row object from from the origin table
                <code class="code">Bugs</code>, and finding rows from the destination table
                <code class="code">Products</code>, representing products related to that bug.
            </p>
<pre class="programlisting">&lt;?php
$bugsTable        = new Bugs();
$bugsRowset       = $bugsTable-&gt;find(1234);
$bug1234          = $bugsRowset-&gt;current();

$productsRowset   = $bug1234-&gt;findManyToManyRowset('Products', 'BugsProducts');
            </pre>
</div>
</div>
<br class="example-break"><p>
            The third and fourth arguments <code class="code">$rule1</code> and <code class="code">$rule2</code> are
            optional. These are strings that name the rule keys in the <code class="code">$_referenceMap</code>
            array of the intersection table.
        </p>
<p>
            The <code class="code">$rule1</code> key names the rule for the relationship from the intersection
            table to the origin table. In this example, this is the relationship from
            <code class="code">BugsProducts</code> to <code class="code">Bugs</code>.
        </p>
<p>
            The <code class="code">$rule2</code> key names the rule for the relationship from the intersection
            table to the destination table. In this example, this is the relationship from
            <code class="code">Bugs</code> to <code class="code">Products</code>.
        </p>
<p>
            Similarly to the methods for finding parent and dependent rows, if you don't specify a
            rule, the method uses the first rule in the <code class="code">$_referenceMap</code> array that
            matches the tables in the relationship. If you need to use a rule other than the first,
            you need to specify the key.
        </p>
<p>
            In the example code above, the rule key is not specified, so the rules used by default
            are the first ones that match. In this case, <code class="code">$rule1</code> is
            <code class="code">'Reporter'</code> and <code class="code">$rule2</code> is <code class="code">'Product'</code>.
        </p>
<div class="example">
<a name="zend.db.table.relationships.fetching.many-to-many.example-by"></a><p class="title"><b>Example 10.144. Fetching a Rowset with the Many-to-many Method By a Specific Rule</b></p>
<div class="example-contents">
<p>
                This example shows geting a Row object from from the origin table
                <code class="code">Bugs</code>, and finding rows from the destination table
                <code class="code">Products</code>, representing products related to that bug.
            </p>
<pre class="programlisting">&lt;?php
$bugsTable        = new Bugs();
$bugsRowset       = $bugsTable-&gt;find(1234);
$bug1234          = $bugsRowset-&gt;current();

$productsRowset   = $bug1234-&gt;findManyToManyRowset('Products', 'BugsProducts', 'Bug');
            </pre>
</div>
</div>
<br class="example-break"><p>
            Alternatively, you can query rows from the destination table in a many-to-many
            relationship using a "magic method." Zend_Db_Table_Row_Abstract invokes the method:
            <code class="code">findManyToManyRowset('&lt;TableClass&gt;', '&lt;IntersectionTableClass&gt;',
            '&lt;Rule1&gt;', '&lt;Rule2&gt;')</code> if you invoke a method matching any of the
            following patterns:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                    <code class="code">$row-&gt;find&lt;TableClass&gt;Via&lt;IntersectionTableClass&gt;
                    ([Zend_Db_Table_Select $select])</code>
                </p></li>
<li><p>
                    <code class="code">$row-&gt;find&lt;TableClass&gt;Via&lt;IntersectionTableClass&gt;By&lt;Rule1&gt;
                    ([Zend_Db_Table_Select $select])</code>
                </p></li>
<li><p>
                    <code class="code">$row-&gt;find&lt;TableClass&gt;Via&lt;IntersectionTableClass&gt;By&lt;Rule1&gt;And&lt;Rule2&gt;
                    ([Zend_Db_Table_Select $select])</code>
                </p></li>
</ul></div>
<p>
            In the patterns above, <code class="code">&lt;TableClass&gt;</code> and
            <code class="code">&lt;IntersectionTableClass&gt;</code> are strings that correspond to the class
            names of the destination table and the intersection table, respectively.
            <code class="code">&lt;Rule1&gt;</code> and <code class="code">&lt;Rule2&gt;</code> are strings that correspond
            to the rule keys in the intersection table that reference the origin table and the
            destination table, respectively.
        </p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
                The table identities and the rule keys named in the method call must match the
                spelling of the class and rule key exactly.
            </p></td></tr>
</table></div>
<div class="example">
<a name="zend.db.table.relationships.fetching.many-to-many.example-magic"></a><p class="title"><b>Example 10.145. Fetching Rowsets using the Magic Many-to-many Method</b></p>
<div class="example-contents">
<p>
                This example shows finding rows in the destination table of a many-to-many
                relationship representing products related to a given bug.
            </p>
<pre class="programlisting">&lt;?php
$bugsTable        = new Bugs();
$bugsRowset       = $bugsTable-&gt;find(1234);
$bug1234          = $bugsRowset-&gt;current();

// Use the default reference rule
$products          = $bug1234-&gt;findProductsViaBugsProducts();

// Specify the reference rule
$products          = $bug1234-&gt;findProductsViaBugsProductsByBug();
            </pre>
</div>
</div>
<br class="example-break">
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.db.table.relationships.cascading"></a>10.8.6. Cascading Write Operations</h3></div></div></div>
<div class="note"><table border="0" summary="Note: Declare DRI in the database:">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.png"></td>
<th align="left">Declare DRI in the database:</th>
</tr>
<tr><td align="left" valign="top">
<p>
                Declaring cascading operations in Zend_Db_Table is intended
                <span class="strong"><strong>only</strong></span> for RDBMS brands that do not support
                declarative referential integrity (DRI).
            </p>
<p>
                For example, if you use MySQL's MyISAM storage engine, or SQLite, these solutions
                do not support DRI. You may find it helpful to declare the cascading operations
                with Zend_Db_Table.
            </p>
<p>
                If your RDBMS implements DRI and the <code class="code">ON DELETE</code> and
                <code class="code">ON UPDATE</code> clauses, you should declare these clauses in your database
                schema, instead of using the cascading feature in Zend_Db_Table. Declaring
                cascading DRI rules in the RDBMS is better for database performance, consistency,
                and integrity.
            </p>
<p>
                Most importantly, do not declare cascading operations both in the RDBMS and in your
                Zend_Db_Table class.
            </p>
</td></tr>
</table></div>
<p>
            You can declare cascading operations to execute against a dependent table when you
            apply an <code class="code">UPDATE</code> or a <code class="code">DELETE</code> to a row in a parent table.
        </p>
<div class="example">
<a name="zend.db.table.relationships.cascading.example-delete"></a><p class="title"><b>Example 10.146. Example of a Cascading Delete</b></p>
<div class="example-contents">
<p>
                This example shows deleting a row in the <code class="code">Products</code> table, which is
                configured to automatically delete dependent rows in the <code class="code">Bugs</code> table.
            </p>
<pre class="programlisting">&lt;?php
$productsTable  = new Products();
$productsRowset = $productsTable-&gt;find(1234);
$product1234    = $productsRowset-&gt;current();

$product1234-&gt;delete();
// Automatically cascades to Bugs table
// and deletes dependent rows.
            </pre>
</div>
</div>
<br class="example-break"><p>
            Similarly, if you use <code class="code">UPDATE</code> to change the value of a primary key in a
            parent table, you may want the value in foreign keys of dependent tables to be updated
            automatically to match the new value, so that such references are kept up to date.
        </p>
<p>
            It's usually not necessary to update the value of a primary key that was generated by a
            sequence or other mechanism. But if you use a <span class="emphasis"><em>natural key</em></span> that may
            change value occasionally, it is more likely that you need to apply cascading updates
            to dependent tables.
        </p>
<p>
            To declare a cascading relationship in the Zend_Db_Table, edit the rules in the
            <code class="code">$_referenceMap</code>. Set the associative array keys <code class="code">'onDelete'</code> and
            <code class="code">'onUpdate'</code> to the string 'cascade' (or the constant
            <code class="code">self::CASCADE</code>). Before a row is deleted from the parent table, or its
            primary key values updated, any rows in the dependent table that refer to the parent's
            row are deleted or updated first.
        </p>
<div class="example">
<a name="zend.db.table.relationships.cascading.example-declaration"></a><p class="title"><b>Example 10.147. Example Declaration of Cascading Operations</b></p>
<div class="example-contents">
<p>
                In the example below, rows in the <code class="code">Bugs</code> table are automatically deleted
                if the row in the <code class="code">Products</code> table to which they refer is deleted. The
                <code class="code">'onDelete'</code> element of the reference map entry is set to
                <code class="code">self::CASCADE</code>.
            </p>
<p>
                No cascading update is done in the example below if the primary key value in the
                parent class is changed. The <code class="code">'onUpdate'</code> element of the reference map
                entry is <code class="code">self::RESTRICT</code>. You can get the same result using the value
                <code class="code">self::NO_ACTION</code>, or by omitting the <code class="code">'onUpdate'</code> entry.
            </p>
<pre class="programlisting">&lt;?php
class BugsProducts extends Zend_Db_Table_Abstract
{
    ...
    protected $_referenceMap    = array(
        'Product' =&gt; array(
            'columns'           =&gt; array('product_id'),
            'refTableClass'     =&gt; 'Products',
            'refColumns'        =&gt; array('product_id'),
            'onDelete'          =&gt; self::CASCADE,
            'onUpdate'          =&gt; self::RESTRICT
        ),
        ...
    );
}
            </pre>
</div>
</div>
<br class="example-break"><div class="sect3" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="zend.db.table.relationships.cascading.notes"></a>10.8.6.1. Notes Regarding Cascading Operations</h4></div></div></div>
<p>
                <span class="strong"><strong>Cascading operations invoked by Zend_Db_Table are not
                atomic.</strong></span>
            </p>
<p>
                This means that if your database implements and enforces referential integrity
                constraints, a cascading <code class="code">UPDATE</code> executed by a Zend_Db_Table class
                conflicts with the constraint, and results in a referential integrity violation.
                You can use cascading <code class="code">UPDATE</code> in Zend_Db_Table
                <span class="emphasis"><em>only</em></span> if your database does not enforce that referential
                integrity constraint.
            </p>
<p>
                Cascading <code class="code">DELETE</code> suffers less from the problem of referential
                integrity violations. You can delete dependent rows as a non-atomic action before
                deleting the parent row that they reference.
            </p>
<p>
                However, for both <code class="code">UPDATE</code> and <code class="code">DELETE</code>, changing the
                database in a non-atomic way also creates the risk that another database user can
                see the data in an inconsistent state. For example, if you delete a row and all its
                dependent rows, there is a small chance that another database client program can
                query the database after you have deleted the dependent rows, but before you delete
                the parent row. That client program may see the parent row with no dependent rows,
                and assume this is the intended state of the data. There is no way for that client
                to know that its query read the database in the middle of a change.
            </p>
<p>
                The issue of non-atomic change can be mitigated by using transactions to isolate
                your change. But some RDBMS brands don't support transactions, or allow clients to
                read "dirty" changes that have not been committed yet.
            </p>
<p>
                <span class="strong"><strong>Cascading operations in Zend_Db_Table are invoked only by
                Zend_Db_Table.</strong></span>
            </p>
<p>
                Cascading deletes and updates defined in your Zend_Db_Table classes are applied if
                you execute the <code class="code">save()</code> or <code class="code">delete()</code> methods on the Row
                class. However, if you update or delete data using another interface, such as a
                query tool or another application, the cascading operations are not applied. Even
                when using <code class="code">update()</code> and <code class="code">delete()</code> methods in the
                Zend_Db_Adapter class, cascading operations defined in your Zend_Db_Table classes
                are not executed.
            </p>
<p>
                <span class="strong"><strong>No Cascading <code class="code">INSERT</code>.</strong></span>
            </p>
<p>
                There is no support for a cascading <code class="code">INSERT</code>. You must insert a row to a
                parent table in one operation, and insert row(s) to a dependent table in a separate
                operation.
            </p>
</div>
</div>
</div>
<div class="navfooter"><table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="zend.db.table.rowset.html">Prev</a> </td>
<td width="20%" align="center"><a accesskey="u" href="zend.db.html">Up</a></td>
<td width="40%" align="right"> <a accesskey="n" href="zend.debug.html">Next</a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">10.7. Zend_Db_Table_Rowset </td>
<td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td>
<td width="40%" align="right" valign="top"> Chapter 11. Zend_Debug</td>
</tr>
</table></div>
<div class="revinfo"></div>
</body>
</html>
